export const cFetch = <T>(url: string, opts?: CustomClientFetchOptions) => {
    const config = useRuntimeConfig()
    const nuxtApp=useNuxtApp()
    return $fetch<ApiResponse<T>>(url, {
        baseURL: config.public.baseURL,
        onRequest: ({options}) => {
            //从自定义配置中知道是否需要携带身份验证信息
            if (opts?.auth) {
                let token: string = userStore().getToken()
                options.headers.set('session_token_key', `${token}`)
            }
        },
        onResponse: ({response}) => {
            // console.log(response)
            if (response.status >= 200 && response.status < 300) {
                if (response._data.code != 200) {
                    showNotify({
                        type: 'danger',
                        message: response._data.message,
                        duration: 2000
                    })
                }
            }
        },
        onResponseError: ({response}) => {
            let status = response.status
            switch (status) {
                case 401:
                    showNotify({
                        type: 'warning',
                        message: '身份验证信息过期',
                        duration: 3000
                    })
                    nuxtApp.runWithContext(function (){navigateTo('/login')})
                    break;
                case 502:
                    showNotify({
                        type: 'danger',
                        message: '网关状态异常',
                        duration: 3000
                    })
                    break;
                default:
                    showNotify({
                        type: 'danger',
                        message: '未知的异常',
                        duration: 3000
                    })
            }
        },
        ...opts?.defaultOpts
    })
}